<template>
  <div class="j_box1">
    <div class="device-layout">
      <!-- 左侧树形控件 -->
      <div class="tree-container">
        <div class="tree-header">
          <h3>客户列表</h3>
          <el-button type="primary" size="small" @click="handleAddCategory">
            <el-icon>
              <Plus />
            </el-icon>
            新增分类
          </el-button>
        </div>
        <div style="height: 760px">
          <el-tree
            ref="treeRef"
            style="height: 100%; padding-top: 10px"
            :data="treeData"
            :props="treeProps"
            node-key="id"
            :default-expand-all="true"
            :expand-on-click-node="false"
            :highlight-current="true"
            class="device-tree"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="tree-node">
                <el-icon class="tree-icon">
                  <UserFilled color="#409eff" />
                </el-icon>
                <span class="tree-label">{{ data.name }}</span>
                <span class="tree-count">01</span>
                <!-- <span v-if="data.count !== undefined" class="tree-count">({{ data.count
              }})</span> -->
              </span>
            </template>
          </el-tree>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="content-container">
        <!-- 面包屑导航 -->
        <div class="breadcrumb-container">
          <el-breadcrumb separator=">">
            <el-breadcrumb-item>设备列表</el-breadcrumb-item>
            <el-breadcrumb-item v-if="currentCategory">
              {{ currentCategory.label }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <!-- 搜索区域 -->
        <div class="search-container" style="position: relative">
          <el-form :model="queryParams" :inline="true" class="search-form">
            <el-form-item label="设备名称">
              <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable />
            </el-form-item>
            <el-form-item label="IMEI" style="position: absolute" class="imei-input">
              <el-input
                v-model="IMEI"
                type="textarea"
                :rows="imeiEows"
                placeholder="请输入设备IMEI(多个回车换行)"
                style="overflow-y: hidden"
                @focus="handleIMEIFocus"
                @blur="handleIMEIBlur"
                @keyup.enter="handleIMEIEnter"
              />
            </el-form-item>
            <el-form-item label="设备类型" style="margin-left: 240px">
              <el-select
                v-model="queryParams.deviceType"
                style="width: 180px"
                placeholder="请选择设备类型"
                clearable
              >
                <el-option v-for="item in devTypeData" :label="item.typeName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="设备状态">
              <el-checkbox v-model="queryParams.isLower" label="包含下级" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon>
                  <Search />
                </el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon>
                  <Refresh />
                </el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-container">
          <el-button type="primary" @click="handleAdd">
            <!-- <el-icon>
              <Plus />
            </el-icon> -->
            新增设备
          </el-button>
          <el-button @click="handleBatchImport">
            <!-- <el-icon>
              <Upload />
            </el-icon> -->
            批量导入
          </el-button>
          <!-- <el-button type="warning" @click="handleExport">
            <el-icon>
              <Download />
            </el-icon>
            导出数据
          </el-button> -->
        </div>

        <!-- 设备表格 -->
        <div class="table-container">
          <el-table
            v-loading="loading"
            :data="filteredDeviceList"
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" align="center" width="55" />
            <el-table-column type="index" width="60" />
            <el-table-column prop="deviceNumber" align="center" label="IMEI" width="180" />

            <el-table-column prop="deviceName" align="center" label="设备名称" width="150" />
            <el-table-column prop="deviceType" align="center" label="设备类型" width="130">
              <template #default="{ row }">
                {{ devTypeData.find((item) => item.id === row.deviceType)?.typeName || "-" }}
              </template>
            </el-table-column>
            <el-table-column prop="activeTime" align="center" label="激活时间" width="150">
              <template #default="{ row }">
                {{ row.activeTime ? row.activeTime.split(" ")[0] : "" }}
              </template>
            </el-table-column>
            <el-table-column prop="sim" align="center" label="设备SIM号" width="170" />
            <el-table-column prop="lastTime" align="center" label="最后在线时间" width="180">
              <template #default="{ row }">
                {{ row.lastTime }}
              </template>
            </el-table-column>
            <el-table-column
              prop="platformExpireTime"
              align="center"
              label="平台到期时间"
              width="130"
            >
              <template #default="{ row }">
                {{ row.platformExpireTime ? row.platformExpireTime.split(" ")[0] : "" }}
              </template>
            </el-table-column>
            <el-table-column prop="expireTime" align="center" label="客户到期时间" width="130">
              <template #default="{ row }">
                {{ row.expireTime ? row.expireTime.split(" ")[0] : "" }}
              </template>
            </el-table-column>
            <el-table-column prop="useStatus" align="center" label="开机状态" width="120">
              <template #default="{ row }">
                {{ row.useStatus == 1 ? "开机" : "关机" }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="300" align="center" fixed="right">
              <template #default="{ row }">
                <el-button
                  v-hasPerm="['system:menu:edit']"
                  type="primary"
                  link
                  size="small"
                  @click.stop="handleEdit(row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-hasPerm="['system:menu:edit']"
                  type="primary"
                  link
                  size="small"
                  @click.stop="salesDevEvent(row)"
                >
                  销售
                </el-button>
                <el-button
                  v-hasPerm="['system:menu:edit']"
                  type="primary"
                  link
                  size="small"
                  @click.stop="activeDevEvent(row)"
                >
                  发送短信
                </el-button>

                <el-button
                  v-hasPerm="['system:menu:edit']"
                  type="danger"
                  link
                  size="small"
                  @click.stop="handleDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页组件 -->
        <div v-if="total > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 设备详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      draggable
      :title="dialogTitle"
      width="50%"
    >
      <div
        style="height: 400px; overflow-y: scroll; scrollbar-width: none; -ms-overflow-style: none"
        class="hide-scrollbar"
      >
        <el-form ref="deviceFormRef" :model="deviceForm" :rules="deviceRules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="设备IMEI" prop="deviceNumber">
                <el-input v-model="deviceForm.deviceNumber" placeholder="请输入设备IMEI" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备ID" prop="deviceNumber">
                <el-input v-model="deviceForm.deviceId" placeholder="请输入设备IMEI" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备类型" prop="deviceType">
                <el-select v-model="deviceForm.deviceType" placeholder="请选择设备类型">
                  <el-option v-for="item in devTypeData" :label="item.typeName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="设备名称" prop="deviceName">
                <el-input v-model="deviceForm.deviceName" placeholder="请输入设备名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备SIM卡号" prop="sim">
                <el-input v-model="deviceForm.sim" placeholder="请输入设备SIM卡号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="ICCID" prop="iccid">
                <el-input v-model="deviceForm.iccid" placeholder="请输入ICCID" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="deviceForm.remark"
                  type="textarea"
                  placeholder="请输入设备名称"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 销售设备对话框 -->
    <el-dialog
      v-model="salesDialogVisible"
      :title="'销售设备'"
      width="60%"
      :close-on-click-modal="false"
      draggable
    >
      <div class="dialog-content">
        <!-- 对话框内容区域 -->
        <el-row>
          <el-col :span="16">
            <el-form
              ref="salesFormRef"
              :model="salesDevForm"
              label-position="top"
              :rules="salesRules"
              label-width="100px"
            >
              <el-form-item label="销售目标客户">
                <el-input v-model="userName" disabled></el-input>
              </el-form-item>
              <el-form-item label="销售时长">
                <el-select v-model="salesDevForm.type" placeholder="请选择销售时长">
                  <el-option
                    v-for="item in salesTime"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="销售设备">
                <el-table :data="salesTable" style="width: 100%">
                  <el-table-column prop="deviceNumber" label="IMEI" />
                  <el-table-column prop="deviceName" label="设备名称" />
                  <el-table-column prop="sim" label="设备SIM卡号" />
                  <el-table-column prop="deviceType" label="设备类型" />
                  <el-table-column prop="username" label="所属客户" />
                </el-table>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <div
              style="
                border: #dcdfe6 1px solid;
                padding: 15px;
                margin-left: 10px;
                height: 500px;
                overflow-y: auto;
              "
            >
              <el-input
                v-model="salesQueryValue"
                style="max-width: 600px"
                placeholder="请输入客户名称"
                class="input-with-select"
              ></el-input>
              <el-tree
                ref="salesTreeRef"
                style="width: 100%; margin-top: 10px"
                :data="salesTreeData"
                :props="salesProps"
                highlight-current
                :expand-on-click-node="false"
                :current-node-key="salesSelectedId"
                :default-expanded-keys="expandedKeys"
                :filter-node-method="filterNode"
                node-key="id"
                @node-click="userNodeClick1"
              ></el-tree>
            </div>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="salesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSalesSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分类管理对话框 -->
    <el-dialog
      v-model="activeDialogVisible"
      :close-on-click-modal="false"
      draggable
      title="发送短信"
      width="600px"
    >
      <el-form ref="activeFormRef" :model="activeForm" :rules="activeRules" label-width="80px">
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="activeForm.type" placeholder="请选择设备类型">
            <el-option
              v-for="item in activeType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="activeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleActiveSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分类管理对话框 -->
    <el-dialog v-model="categoryDialogVisible" title="分类管理" width="600px">
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="上级分类" prop="parentId">
          <el-tree-select
            v-model="categoryForm.parentId"
            :data="treeData"
            :props="treeProps"
            placeholder="请选择上级分类（可选）"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCategorySubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设备导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="设备批量导入"
      width="600px"
      :close-on-click-modal="false"
      @close="handleCloseImport"
    >
      <div class="import-content">
        <div class="import-tips">
          <el-alert title="导入说明" type="info" :closable="false" show-icon>
            <template #default>
              <div>
                <p>1. 请先下载导入模板，按照模板格式填写设备信息</p>
                <p>2. 支持 .xlsx 和 .xls 格式的文件</p>
                <p>3. 文件大小不能超过 10MB</p>
                <p>4. 设备IMEI不能重复</p>
              </div>
            </template>
          </el-alert>
        </div>

        <div class="template-download">
          <el-button type="primary" plain @click="handleDownloadTemplate">
            <el-icon>
              <Download />
            </el-icon>
            下载导入模板
          </el-button>
        </div>

        <div class="file-upload">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="1"
            :on-exceed="handleFileExceed"
            :http-request="handleUpload"
            accept=".xlsx,.xls"
            drag
          >
            <el-icon class="el-icon--upload">
              <Upload />
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">只能上传 .xlsx/.xls 文件，且不超过 10MB</div>
            </template>
          </el-upload>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseImport">取消</el-button>
          <el-button type="primary" :loading="uploading" @click="uploadRef?.submit()">
            {{ uploading ? "导入中..." : "开始导入" }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog
      v-model="importResultDialogVisible"
      title="导入结果"
      width="500px"
      @close="handleCloseResult"
    >
      <div class="import-result">
        <div class="result-summary">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="result-item success">
                <el-icon>
                  <Check />
                </el-icon>
                <div>
                  <div class="count">{{ importResult.successCount }}</div>
                  <div class="label">成功导入</div>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="result-item error">
                <el-icon>
                  <Close />
                </el-icon>
                <div>
                  <div class="count">{{ importResult.failureCount }}</div>
                  <div class="label">导入失败</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <div v-if="importResult.errors && importResult.errors.length > 0" class="error-list">
          <h4>错误详情：</h4>
          <el-scrollbar max-height="200px">
            <div class="error-items">
              <div v-for="(error, index) in importResult.errors" :key="index" class="error-item">
                <el-icon class="error-icon">
                  <Warning />
                </el-icon>
                <span>{{ error }}</span>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleCloseResult">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import type { TabsPaneContext } from "element-plus";
import UserAPI from "@/api/system/user.api";

import DeviceAPI from "@/api/system/device.api";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Upload,
  Download,
  Edit,
  View,
  Delete,
  Folder,
  Document,
  Check,
  Close,
  Warning,
} from "@element-plus/icons-vue";
import { min } from "lodash-es";
const salesProps = {
  children: "children",
  label: "name",
};
// 响应式数据

const activeDialogVisible = ref(false);
const activeForm = ref({
  id: undefined,
  type: 1,
});
const activeRules = ref([]);
const activeFormRef = ref(null);
const activeType = ref([
  { label: "小狼星", value: 1 },
  { label: "小博物联", value: 2 },
  { label: "几米", value: 3 },
]);

// 批量导入相关
const importDialogVisible = ref(false);
const importResultDialogVisible = ref(false);
const uploadRef = ref();
const importResult = ref({
  successCount: 0,
  failureCount: 0,
  errors: [],
});
const uploading = ref(false);

const salesDialogVisible = ref(false);
const salesFormRef = ref(null);
const salesDevForm = ref({
  id: undefined,
  userId: undefined,
  type: 9,
});
const expandedKeys = ref([]);
const userName = ref("");

const salesSelectedId = ref(1);
const salesTreeData = ref([]);
const salesTreeRef = ref(null);
const salesQueryValue = ref("");
const activeName = ref("1");
const loading = ref(false);
const dialogVisible = ref(false);
const categoryDialogVisible = ref(false);
const dialogTitle = ref("新增设备");
const deviceFormRef = ref();
const categoryFormRef = ref();
const treeRef = ref();
const currentCategory = ref(null);
const IMEI = ref("");
const imeiEows = ref(1);
// 树形控件配置
const treeProps = {
  children: "children",
  label: "label",
  value: "id",
};

const devTypeData = ref([]);

const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  deviceName: "",
  deviceNumbers: [],
  deviceType: "",
  userId: 0,
  isLower: true,
});

// 树形数据
const treeData = ref([]);

// 搜索表单
const searchForm = reactive({
  deviceName: "",
  deviceType: "",
  status: "",
});
// 在script setup中添加以下代码:
const isIMEITextarea = ref(false);

// IMEI输入框点击事件
const handleIMEIClick = () => {
  isIMEITextarea.value = true;
};

// IMEI输入框回车事件
const handleIMEIEnter = (value) => {
  console.log("回车事件", value);
};

// 确定发送短信
const handleActiveSubmit = async () => {
  console.log("activeForm.value", activeForm.value);

  const { data } = await DeviceAPI.activeDev(activeForm.value);
  console.log(data);
  if (data.code == 0) {
    ElMessage.success("发送成功");
    activeDialogVisible.value = false;
  } else if (data.code == 1) {
    ElMessage.error("设备激活失败");
  }
};

// IMEI输入框失焦事件
const handleIMEIBlur = () => {
  imeiEows.value = 1;
};
// IMEI输入框聚焦事件
const handleIMEIFocus = () => {
  imeiEows.value = 5;
};
// 设备表单
const deviceForm = reactive({
  id: undefined,
  deviceId: "",
  deviceName: "",
  deviceType: "",
  deviceNumber: "",
  sim: "",
  iccid: "",
  remark: "",
});
// 销售设备
function salesDevEvent(row) {
  console.log(row);
  salesTable.value = [];
  salesTable.value.push(row);
  salesDevForm.value.id = row.id;
  salesDialogVisible.value = true;
}
// 发送短信
function activeDevEvent(row) {
  console.log(row);
  activeForm.value.type = 1;
  activeForm.value.id = row.id;
  activeDialogVisible.value = true;
}

const handleSalesSubmit = async () => {
  const { data } = await DeviceAPI.salesDev(salesDevForm.value);
  console.log(data);
  if (data.code == 0) {
    ElMessage.success("销售成功");
    salesDialogVisible.value = false;
    getDeviceList();
  }
};

function userNodeClick1(value) {
  console.log("node", value);
  userName.value = value.userName;
  salesDevForm.value.userId = value.id;
}
const filterNode: FilterNodeMethodFunction = (value: string, data: Tree) => {
  if (!value) return true;
  console.log(data, value);
  return data.userName.includes(value);
};
// 分类表单
const categoryForm = reactive({
  id: "",
  name: "",
  parentId: "",
  sort: 0,
  description: "",
});
// 销售设备表单数据
const salesFormData = reactive({
  userId: "",
});
// 销售设备表单验证规则
const salesRules = {
  userId: [{ required: true, message: "请选择用户", trigger: "change" }],
};
// 表单验证规则
const deviceRules = {
  deviceName: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
  deviceType: [{ required: true, message: "请选择设备类型", trigger: "change" }],
  // deviceNumber: [
  //   { required: true, message: "请输入设备编号", trigger: "blur" },
  //   { min: 4, message: "请输入正确的设备编号", trigger: "blur" },
  // ],
  // sim: [
  //   { required: true, message: "请输入设备SIM卡号", trigger: "blur" },
  //   { pattern: /^[0-9]{11,20}$/, message: "请输入正确格式的SIM卡号", trigger: "blur" },
  // ],
  iccid: [
    // { required: true, message: "请输入设备ICCID号", trigger: "blur" },
    // { pattern: /^[0-9A-Fa-f]{18,22}$/, message: "请输入正确格式的ICCID", trigger: "blur" },
  ],
};

const categoryRules = {
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
};

const salesTime = ref([
  {
    label: "不限制",
    value: 9,
  },
  {
    label: "三年",
    value: 8,
  },
  {
    label: "两年",
    value: 7,
  },
  {
    label: "一年",
    value: 6,
  },
  {
    label: "半年",
    value: 5,
  },
  {
    label: "三月",
    value: 4,
  },
  {
    label: "三月",
    value: 3,
  },
  {
    label: "二月",
    value: 2,
  },
  {
    label: "一月",
    value: 1,
  },
]);
const salesTable = ref([]);
// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 设备列表数据
const deviceList = ref([]);

// 选中的行
const selectedRows = ref([]);

async function getDeviceList() {
  const { data } = await DeviceAPI.getPage(queryParams.value);
  deviceList.value = data.data.records;
  total.value = parseInt(data.data.total);
}

async function getTreeData() {
  const { data } = await UserAPI.getTreeInfo();
  treeData.value = data.data;
  salesTreeData.value = data.data;
  collectExpandedIds(salesTreeData.value);
  console.log(treeData.value);
}

function collectExpandedIds(nodes) {
  nodes.forEach((node) => {
    if (node.children && node.children.length > 0) {
      expandedKeys.value.push(node.id);
      // 递归处理子节点
      collectExpandedIds(node.children);
    }
  });
}

// 计算属性 - 根据选中的分类过滤设备列表
const filteredDeviceList = computed(() => {
  if (!currentCategory.value || currentCategory.value.id === "all") {
    return deviceList.value;
  }

  // 获取当前分类及其所有子分类的ID
  const getCategoryIds = (category) => {
    const ids = [category.id];
    if (category.children) {
      category.children.forEach((child) => {
        ids.push(...getCategoryIds(child));
      });
    }
    return ids;
  };
  const categoryIds = getCategoryIds(currentCategory.value);
  return deviceList.value.filter((device) => categoryIds.includes(device.categoryId));
});

// 方法定义
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

const handleNodeClick = (data) => {
  // currentCategory.value = data
  console.log(data);
  queryParams.value.userId = data.id;
  getDeviceList();

  // ElMessage.info(`已选择分类：${data}`)
};

const handleAddCategory = () => {
  Object.assign(categoryForm, {
    id: "",
    name: "",
    parentId: "",
    sort: 0,
    description: "",
  });
  categoryDialogVisible.value = true;
};

const handleCategorySubmit = async () => {
  if (!categoryFormRef.value) return;

  try {
    await categoryFormRef.value.validate();
    // 这里添加保存分类的逻辑
    ElMessage.success("分类保存成功");
    categoryDialogVisible.value = false;
  } catch (error) {
    console.log("验证失败:", error);
  }
};

const handleSearch = () => {
  loading.value = true;

  // 将deviceNumbers转换为数组（如果是字符串的话）
  let deviceNumbersArray = [];

  // 按换行符、逗号或分号分割字符串
  deviceNumbersArray = IMEI.value
    .split(/[\n,;]/) // 支持换行符、逗号、分号分割
    .map((item) => item.trim()) // 去除空格
    .filter((item) => item.length > 0); // 过滤空字符串

  console.log("IMEI输入框回车事件", queryParams.value.isLower);

  // 更新queryParams中的deviceNumbers为数组格式
  queryParams.value.deviceNumbers = deviceNumbersArray;

  getDeviceList();
  loading.value = false;
  // 模拟搜索请求
  // setTimeout(() => {
  //   loading.value = false
  //   ElMessage.success('搜索完成')
  // }, 1000)
};

const handleReset = () => {
  ((queryParams.value.pageNum = 1),
    (queryParams.value.pageSize = 10),
    (queryParams.value.deviceName = ""),
    (queryParams.value.deviceNumbers = []),
    (queryParams.value.deviceType = ""),
    (queryParams.value.userId = 0),
    (queryParams.value.isLower = true));
  IMEI.value = "";

  getDeviceList();
};

const getdevtype = async () => {
  const obj = {
    typeName: "",
  };
  const { data } = await DeviceAPI.getdevType(obj);
  devTypeData.value = data.data;
  console.log("设备类型", devTypeData.value);
};

const handleAdd = () => {
  dialogTitle.value = "新增设备";
  Object.assign(deviceForm, {
    id: undefined,
    deviceId: "",
    deviceName: "",
    deviceType: 1,
    deviceNumber: "",
    sim: "",
    iccid: "",
    remark: "",
  });

  // 清除表单验证
  nextTick(() => {
    deviceFormRef.value?.clearValidate();
  });
  dialogVisible.value = true;
};

const handleEdit = (row: any) => {
  dialogTitle.value = "编辑设备";
  // Object.assign(deviceForm, { ...row })
  deviceForm.id = row.id;
  deviceForm.deviceId = row.deviceId;
  deviceForm.deviceName = row.deviceName;
  deviceForm.deviceType = row.deviceType;
  deviceForm.deviceNumber = row.deviceNumber;
  deviceForm.sim = row.sim;
  deviceForm.iccid = row.iccid;
  deviceForm.remark = row.remark;
  dialogVisible.value = true;
};

const handleView = (row: any) => {
  ElMessage.info(`查看设备详情: ${row.deviceName}`);
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除设备 "${row.deviceName}" 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    DeviceAPI.deleteDev(row.id).then((res) => {
      if (res.data.code == 0) {
        ElMessage.success("删除成功");
        getDeviceList();
      }
    });
  });
};

const handleBatchImport = () => {
  importDialogVisible.value = true;
};

// 文件超出限制处理
const handleFileExceed = () => {
  ElMessage.warning("只能上传一个文件");
};

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    const response = await DeviceAPI.downloadTemplate();
    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "设备导入模板.xlsx";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success("模板下载成功");
  } catch (error) {
    ElMessage.error("模板下载失败");
  }
};

// 文件上传
const handleUpload = async (options: any) => {
  const { file } = options;

  // 验证文件类型
  const isExcel =
    file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    file.type === "application/vnd.ms-excel";
  if (!isExcel) {
    ElMessage.error("只能上传 Excel 文件");
    return;
  }

  // 验证文件大小（10MB）
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error("文件大小不能超过 10MB");
    return;
  }

  uploading.value = true;

  try {
    const result = await DeviceAPI.import(file);
    importResult.value = result.data;
    importDialogVisible.value = false;
    importResultDialogVisible.value = true;

    if (result.data.successCount > 0) {
      ElMessage.success(`成功导入 ${result.data.successCount} 条设备数据`);
      getDeviceList(); // 刷新列表
    }
  } catch (error) {
    ElMessage.error("导入失败，请检查文件格式");
  } finally {
    uploading.value = false;
  }
};

// 显示错误信息
const handleShowResult = () => {
  importResultDialogVisible.value = true;
};

// 关闭结果弹窗
const handleCloseResult = () => {
  importResultDialogVisible.value = false;
  importResult.value = {
    successCount: 0,
    failureCount: 0,
    errors: [],
  };
};

// 关闭导入弹窗
const handleCloseImport = () => {
  importDialogVisible.value = false;
  uploadRef.value?.clearFiles();
};

const handleExport = () => {
  ElMessage.info("导出数据功能开发中...");
};

const handleSubmit = () => {
  deviceFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // deviceForm.deviceId = deviceForm.deviceNumber.substring(4);
      // console.log(deviceForm.deviceId);
      if (deviceForm.id) {
        //编辑
        DeviceAPI.updateDev(deviceForm).then((res) => {
          if (res.data.code == 0) {
            ElMessage.success("编辑成功");
            dialogVisible.value = false;
            getDeviceList();
          }
        });
      } else {
        // 新增
        DeviceAPI.createDev(deviceForm).then((res) => {
          if (res.data.code == 0) {
            ElMessage.success("新增成功");
            dialogVisible.value = false;
            getDeviceList();
          }
        });
      }
      dialogVisible.value = false;
    }
  });
};

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  handleSearch();
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  handleSearch();
};

// 辅助方法
const getDeviceTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    gps: "GPS定位器",
    recorder: "行车记录仪",
    temperature: "温度传感器",
    fuel: "油量传感器",
  };
  return typeMap[type] || type;
};

const getDeviceTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    gps: "primary",
    recorder: "success",
    temperature: "warning",
    fuel: "info",
  };
  return tagMap[type] || "";
};

const getStatusName = (status: string) => {
  const statusMap: Record<string, string> = {
    online: "在线",
    offline: "离线",
    error: "故障",
  };
  return statusMap[status] || status;
};

const getStatusTag = (status: string) => {
  const tagMap: Record<string, string> = {
    online: "success",
    offline: "info",
    error: "danger",
  };
  return tagMap[status] || "";
};
// 根据视口宽度动态设置根字体大小
function setRem() {
  const baseSize = 16; // 基准值16px
  const scale = document.documentElement.clientWidth / 1920; // 假设设计稿宽度为1920px
  document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + "px";
}
// 初始化
setRem();
// 窗口大小变化时重新计算
window.addEventListener("resize", setRem);

watch(salesQueryValue, (val) => {
  salesTreeRef.value!.filter(val);
});
onMounted(() => {
  getTreeData();
  getDeviceList();
  getdevtype();
  pagination.total = deviceList.value.length;
});
</script>

<style lang="scss" scoped>
.j_box1 {
  // padding: 15px;
  // background-color: #fff;
  height: 100%;
  padding: 10px;
  .imei-input {
    z-index: 99;

    :deep(.el-textarea__inner) {
      scrollbar-width: none !important;
      -ms-overflow-style: none !important;

      &::-webkit-scrollbar {
        display: none !important;
        width: 0 !important;
      }
    }
  }

  .device-management {
    // ... existing code ...

    // 添加以下CSS规则来隐藏IMEI输入框的滚动条
    :deep(.el-textarea__inner) {
      scrollbar-width: none;
      /* Firefox */
      -ms-overflow-style: none;
      /* IE and Edge */

      &::-webkit-scrollbar {
        display: none;
        /* Chrome, Safari and Opera */
      }
    }

    // ... existing code ...
  }

  .device-layout {
    display: flex;
    height: 100%;
    gap: 15px;
  }

  .tree-container {
    width: 280px;
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    border: 1px solid #e9ecef;
    display: flex;
    flex-direction: column;
    height: 100%;

    .tree-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #e9ecef;
      flex-shrink: 0;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #3060ff;
      }
    }

    .device-tree {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
      max-height: calc(100% - 80px);
      padding-right: 5px;

      // 隐藏滚动条但保持滚动功能
      scrollbar-width: none;
      /* Firefox */
      -ms-overflow-style: none;
      /* IE and Edge */

      &::-webkit-scrollbar {
        display: none;
        /* Chrome, Safari and Opera */
      }

      :deep(.el-tree-node__content) {
        height: 28px;
        border-radius: 6px;
        margin-bottom: 2px;
        transition: all 0.3s ease;

        &:hover {
          height: 28px;

          background-color: rgba(48, 96, 255, 0.1);
        }
      }

      :deep(.el-tree-node.is-current > .el-tree-node__content) {
        background-color: #3060ff;
        color: white;
        height: 36px;

        .tree-count {
          color: rgba(255, 255, 255, 0.8);
        }
      }

      .tree-node {
        display: flex;
        align-items: center;
        width: 100%;
        padding-right: 10px;

        .tree-icon {
          margin-right: 8px;
          font-size: 14px;
        }

        .tree-label {
          flex: 1;
          font-size: 14px;
        }

        .tree-count {
          font-size: 12px;
          color: #999;
          margin-left: 3px;
        }
      }
    }
  }

  .content-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .breadcrumb-container {
      margin-bottom: 15px;
      padding: 10px 0;
      border-bottom: 1px solid #e9ecef;

      :deep(.el-breadcrumb__item) {
        font-size: 14px;
      }
    }

    .search-container {
      margin-bottom: 15px;
      padding: 20px;
      background: #f8f9fa;
      border-radius: 8px;
      border: 1px solid #e9ecef;

      .search-form {
        margin: 0;

        :deep(.el-form-item) {
          margin-bottom: 0;
          margin-right: 20px;
        }
      }
    }

    .action-container {
      margin-bottom: 15px;
      display: flex;
      gap: 10px;
    }

    .table-container {
      flex: 1;
      overflow: hidden;
      border: 1px solid #e9ecef;
      border-radius: 8px;

      :deep(.el-table) {
        height: 100%;
      }
    }

    .pagination-container {
      margin-top: 15px;
      display: flex;
      justify-content: flex-end;
    }
  }

  :deep(.el-tabs__item) {
    font-size: 16px;
    font-weight: 500;
  }

  :deep(.el-dialog) {
    .el-form-item__label {
      font-weight: 500;
    }
  }

  // 导入对话框样式
  .import-content {
    .import-tips {
      margin-bottom: 20px;

      :deep(.el-alert__content) {
        p {
          margin: 5px 0;
          line-height: 1.5;
        }
      }
    }

    .template-download {
      text-align: center;
      margin: 20px 0;
    }

    .file-upload {
      margin-top: 20px;

      :deep(.el-upload-dragger) {
        border: 2px dashed #d9d9d9;
        border-radius: 6px;
        width: 100%;
        height: 180px;
        text-align: center;
        position: relative;
        overflow: hidden;
        transition: border-color 0.3s;

        &:hover {
          border-color: #409eff;
        }
      }
    }
  }

  // 导入结果样式
  .import-result {
    .result-summary {
      margin-bottom: 20px;

      .result-item {
        display: flex;
        align-items: center;
        padding: 15px;
        border-radius: 8px;

        &.success {
          background-color: #f0f9ff;
          border: 1px solid #e1f5fe;

          .el-icon {
            color: #52c41a;
            font-size: 24px;
            margin-right: 12px;
          }

          .count {
            font-size: 24px;
            font-weight: bold;
            color: #52c41a;
          }
        }

        &.error {
          background-color: #fff2f0;
          border: 1px solid #ffccc7;

          .el-icon {
            color: #ff4d4f;
            font-size: 24px;
            margin-right: 12px;
          }

          .count {
            font-size: 24px;
            font-weight: bold;
            color: #ff4d4f;
          }
        }

        .label {
          font-size: 14px;
          color: #666;
          margin-top: 4px;
        }
      }
    }

    .error-list {
      h4 {
        margin: 0 0 10px 0;
        font-size: 14px;
        color: #333;
      }

      .error-items {
        .error-item {
          display: flex;
          align-items: center;
          padding: 8px 12px;
          margin-bottom: 8px;
          background-color: #fff2f0;
          border-radius: 4px;
          border-left: 3px solid #ff4d4f;

          .error-icon {
            color: #ff4d4f;
            margin-right: 8px;
            flex-shrink: 0;
          }

          span {
            font-size: 13px;
            color: #666;
            line-height: 1.4;
          }
        }
      }
    }
  }
}
</style>
